package org.jeecg.modules.shiro.authc.interceptor;

import org.jeecg.modules.shiro.authc.config.DynamicDataSource;
import org.jeecg.modules.shiro.authc.config.DynamicDataSourceContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据源切换拦截器
 * @author sakur
 * @since 2022/11/15
 */
public class DatabaseInterceptor implements HandlerInterceptor {

    @Resource
    private Statement statement;

    @Resource
    private DynamicDataSource dynamicDataSource;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String tenantKey = request.getHeader("tenant");
        ResultSet r;
        try {
            r = statement.executeQuery("select * from tenant_datasource.tenant_datasource where tenant_key = '" + tenantKey + "'");
            if (r.next()) {
                String url = r.getString("url");
                String u = r.getString("username");
                String p = r.getString("password");
                r.close();
                //初始化数据源
                dynamicDataSource.setDataSources(tenantKey, url, u, p);
                //切换数据源
                DynamicDataSourceContextHolder.setDataSourceKey(tenantKey);
            } else {
                r.close();
                throw new SQLException("no tenant datasource");
            }
            return true;
        } catch (SQLException | NullPointerException e) {
            System.out.println("statement error");
            DynamicDataSourceContextHolder.setDataSourceKey("master");
        }
        return true;
    }
}
